package com.huanwei.login_regist;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.facebook.stetho.common.LogUtil;
import com.huanwei.cc.R;
import com.huanwei.cc.bean.KeBiao;
import com.huanwei.cc.utils.ALL_CONFIG;
import com.huanwei.cc.utils.JSONUtils;
import com.huanwei.http.API;
import com.huanwei.http.Okhttp;


import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import lib.kingja.switchbutton.SwitchMultiButton;


/**
 * 人员定位
 */
public class MarkerActivity extends BaseActivity implements LocationSource, AMapLocationListener, AMap.OnMarkerClickListener, AMap.InfoWindowAdapter {


    Bundle mSavedInstanceState;
    @BindView(R.id.vvv)
    SwitchMultiButton vvv;
    private AMap aMap;
    private MapView mapView;
    private UiSettings mUiSettings;
    private OnLocationChangedListener mLocationLinstener;
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;

    private View infoWindow = null;
    private TextView mTvDogName;
    private LinearLayout mLlother;
    private Marker mMarkMyLocation;
    private Marker currentMarker;
    private double mLocatinLat;
    private double mLocationLon;

    //    113.758231,23.026998
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_marker);
        ButterKnife.bind(this);

        vvv.setOnSwitchListener(new SwitchMultiButton.OnSwitchListener() {
            @Override
            public void onSwitch(int position, String tabText) {
                Log.e("8888", "xx" + position);
                qiehuan(position);
//                Toast.makeText(MarkerActivity.this, tabText, Toast.LENGTH_SHORT).show();
            }
        });
        RelativeLayout viewById = (RelativeLayout) findViewById(R.id.img_back);
        viewById.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();

            }
        });

        mSavedInstanceState = savedInstanceState;
    }

    @Override
    protected void initView() {
        super.initView();
        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(mSavedInstanceState);// 此方法必须重写
        if (aMap == null) {
            aMap = mapView.getMap();
            aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
                @Override
                public void onMapLoaded() {
                    aMap.setMapType(AMap.MAP_TYPE_NORMAL);

                    setcenter();
                }
            });

        }
        mUiSettings = aMap.getUiSettings();
        mUiSettings.setLogoPosition(2);//设置高德地图logo位置
        mUiSettings.setZoomControlsEnabled(true);
        mUiSettings.setTiltGesturesEnabled(false);

        aMap.setLocationSource(this);// 设置定位监听
        aMap.setMyLocationEnabled(true);
        aMap.setOnMarkerClickListener(this);
        aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式

//        initLocation();
        //中心点设置

        onTouchHide();

        getRealTimeTrack();
    }

    /**
     * 系统小蓝点
     * 设定
     */
    private void setMyLocationStyleIcon() {
//		 自定义系统定位小蓝点

        MyLocationStyle myLocationStyle = new MyLocationStyle();
        ImageView iv = new ImageView(this);
        FrameLayout.LayoutParams fmIv = new FrameLayout.LayoutParams(1, 1);
        iv.setImageResource(R.mipmap.my_dog);
        iv.setLayoutParams(fmIv);
        BitmapDescriptor markerIcon = BitmapDescriptorFactory.fromView(iv);
        myLocationStyle.myLocationIcon(markerIcon);// 设置小蓝点的图标
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        myLocationStyle.strokeWidth(0f);// 设置圆形的边框粗细
        myLocationStyle.anchor(0.5f, 0.9f);
        aMap.setMyLocationStyle(myLocationStyle);
    }


    private void initLocation() {

        locationClient = new AMapLocationClient(getApplicationContext());
        locationOption = new AMapLocationClientOption();

        // 设置定位模式为高精度模式
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        locationOption.setNeedAddress(true);
        // 设置定位监听
        locationClient.setLocationListener(this);
        //每两秒定位一次
        locationOption.setInterval(2000);
        locationOption.setOnceLocation(true);
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();

    }


    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mLocationLinstener = onLocationChangedListener;
    }

    @Override
    public void deactivate() {
        mLocationLinstener = null;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation != null
                    && aMapLocation.getErrorCode() == 0) {

                if (mLocationLinstener != null) {
                    mLocationLinstener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                }
                mLocatinLat = aMapLocation.getLatitude();
                mLocationLon = aMapLocation.getLongitude();

//                setMyStopLoca(new LatLng(mLocatinLat, mLocationLon));
//                setAroundMark(new LatLng(mLocatinLat, mLocationLon));


            }
        } else {
            //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
            LogUtil.d("location Error, ErrCode:"
                    + aMapLocation.getErrorCode() + ", errInfo:"
                    + aMapLocation.getErrorInfo());
        }
    }

    private void setcenter() {
        LatLng marker1 = new LatLng(Double.valueOf(ALL_CONFIG.Latitude), Double.valueOf(ALL_CONFIG.Longitude));
        //设置中心点和缩放比例
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(marker1));
        aMap.moveCamera(CameraUpdateFactory.zoomTo(12));
    }

    private void setMyStopLoca(final LatLng latlng) {
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 17f));

        if (mMarkMyLocation != null) {
            mMarkMyLocation.destroy();
            mMarkMyLocation = null;
        }


        if (mMarkMyLocation == null) {
            final MarkerOptions markerOptions = new MarkerOptions();
            //markerOptions.snippet(dogId);
            // 设置Marker点击之后显示的标题
            markerOptions.setFlat(false);
            markerOptions.anchor(0.5f, 0.7f);
            markerOptions.zIndex(25);
            markerOptions.zIndex(90);
            MyLocationMarkerView myLocationMarkerView = new MyLocationMarkerView(MarkerActivity.this, getmAdaptationClass());


            BitmapDescriptor markerIcon = BitmapDescriptorFactory.fromView(myLocationMarkerView);


            markerOptions.icon(markerIcon);
            markerOptions.position(new LatLng(latlng.latitude + 0.1, latlng.longitude + 0.1));
            mMarkMyLocation = aMap.addMarker(markerOptions);

        } else {
            mMarkMyLocation.setPosition(latlng);
        }
    }

    MyLocationMarkerView manMarkerWoman;
    MarkerOptions markerOptionsWoman;
    BitmapDescriptor markerIconWoman;

    /**
     * 小母狗
     *
     * @param latlng
     */
    private void setAroundMark(final LatLng latlng, String name, final String icon) {


        markerOptionsWoman = new MarkerOptions();
        // 设置Marker点击之后显示的标题
        markerOptionsWoman.setFlat(false);
        markerOptionsWoman.anchor(0.5f, 0.7f);
        markerOptionsWoman.zIndex(25);
        markerOptionsWoman.zIndex(90);
        markerOptionsWoman.title(name + "," + icon);
        markerOptionsWoman.snippet(name + "," + icon);
        manMarkerWoman = new MyLocationMarkerView(MarkerActivity.this, getmAdaptationClass());
        Log.e("11111", "xx" + name);
        manMarkerWoman.setmCirHead2(R.drawable.im_ywls);
        markerIconWoman = BitmapDescriptorFactory.fromView(manMarkerWoman);

        markerOptionsWoman.icon(markerIconWoman);
//        manMarkerWoman = new MyLocationMarkerView(getActivity(), getmAdaptationClass());
//        manMarkerWoman.setmCirHead(R.mipmap.my_dog_test);
//
//        BitmapDescriptor markerIcon = BitmapDescriptorFactory.fromView(manMarkerWoman);
//
//
//        markerOptionsWoman.icon(markerIcon);
        markerOptionsWoman.position(new LatLng(latlng.latitude, latlng.longitude));
        aMap.addMarker(markerOptionsWoman);


    }


    @Override
    public boolean onMarkerClick(final Marker marker) {


        if (currentMarker != null) {
            currentMarker.hideInfoWindow();
            currentMarker = null;
        }
        //新建currentMarker保存状态，当点击非mark区域的时候将marker的InfoWindow隐藏
        currentMarker = marker;
        marker.showInfoWindow();
        mLlother.setBackgroundResource(R.drawable.infowinow_background);
        return true;


    }


    @Override
    public View getInfoWindow(Marker marker) {
        infoWindow = getLayoutInflater().inflate(R.layout.infowindow_other, null);
        mLlother = (LinearLayout) infoWindow.findViewById(R.id.ll_info_other);
        mTvDogName = (TextView) infoWindow.findViewById(R.id.dog_name);
        mTvDogName.setTextColor(getResources().getColor(R.color.main_font_green));
        mTvDogName.setText(marker.getTitle());


        return infoWindow;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    private void onTouchHide() {
        aMap.setOnMapTouchListener(new AMap.OnMapTouchListener() {
            @Override
            public void onTouch(MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        if (currentMarker != null) {
                            currentMarker.hideInfoWindow();
                            currentMarker = null;

                        }
                        break;
                }
            }
        });
    }


    public void getRealTimeTrack() {
        API.getmyCurriculums(new Okhttp.Objectcallback() {
            @Override
            public void onsuccess(String st) {
                if (ALL_CONFIG.Debug) {
                    Log.e("711getRealTimeTrack", st);
                }
                KeBiao getLocations_bean = JSONUtils.parseJSON(st, KeBiao.class);
                if (getLocations_bean.isIssuccess() == true) {
                    List<KeBiao.DataBean> info = getLocations_bean.getData();
                    for (int i = 0; i < info.size(); i++) {
                        String address = info.get(i).getAddress();
                        String[] split = address.split(",");
                        setAroundMark(new LatLng(Double.valueOf(split[0]), Double.valueOf(split[1])), info.get(i).getUser_name(), info.get(i).getUser_account());
                    }


                }

            }

            @Override
            public void onFalia(int code, String errst) {

            }
        });
    }


    public void qiehuan(int key) {
        if (key == 1) {
            if (aMap == null) {
                aMap = mapView.getMap();
                aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
                    @Override
                    public void onMapLoaded() {
                        aMap.setMapType(AMap.MAP_TYPE_SATELLITE);

                    }
                });

            } else {
                aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
            }

        } else {
            if (aMap == null) {
                aMap = mapView.getMap();
                aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
                    @Override
                    public void onMapLoaded() {


                    }
                });

            } else {
                aMap.setMapType(AMap.MAP_TYPE_NORMAL);
            }

        }

    }
}
